<template>
  <div>
    <el-form :model="form" inline>
      <el-form-item label="试卷标题">
        <el-input v-model="form.title" placeholder="请输入试卷标题"></el-input>
      </el-form-item>
      <el-form-item label="考试时间">
        <DatePicker
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          v-model="form.time"
          placeholder="请输入结束时间"
        ></DatePicker>
      </el-form-item>
      <el-button type="primary" @click="submit" icon="el-icon-check"
        >提交</el-button
      >
      <el-button type="primary" @click="reset" icon="el-icon-refresh"
        >重置</el-button
      >
      <el-button type="danger" @click="batchDelete" icon="el-icon-delete"
        >批量删除</el-button
      >
    </el-form>
    <el-table :data="tableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="试卷标题" prop="title"></el-table-column>
      <el-table-column label="考试科目" prop="subjectId">
        <template slot-scope="scope">
          <span v-for="item in subjects" :key="item.id">
            <span v-if="scope.row.subjectId == item.id">
              {{ item.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" prop="userName"></el-table-column>
      <el-table-column label="创建时间" prop="createTime"></el-table-column>
      <el-table-column label="考试时间" prop="testTime">
        <template slot-scope="scope">
          {{ scope.row.testTime | formatTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="detail(scope.row)"
            size="small"
            icon="el-icon-s-check"
            >查看</el-button
          >
          <el-button
            icon="el-icon-delete"
            type="danger"
            @click="deleteHandler(scope.row)"
            size="small"
            >刪除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import zhiZhaoApi from "@/api/questionItem/questionItem";
import { DatePicker } from "element-ui";
import subjectApi from "@/api/subject/index";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: { DatePicker },
  props: {},
  data() {
    //这里存放数据
    return {
      tableData: [],
      form: { title: "", time: null },
      currentPage: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [], //批量删除时选择的内容
      subjects: [],
    };
  },
  filters: {
    formatTime(value) {
      if (value === 0) {
        return "";
      }
      const minutes = Math.floor(value / 60); // 计算分钟数
      let seconds = value % 60; // 计算剩余的秒数
      seconds = seconds == 0 ? "" : seconds + "秒";
      return `${minutes}分钟${seconds}`; // 返回格式化后的时间字符串
    },
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    /**
     * 批量删除
     */
    batchDelete() {
      this.$confirm(
        "此操作将永久删除该套试卷及相关考试记录，是否继续？",
        "提示",
        { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
      )
        .then(() => {
          zhiZhaoApi.batchDelete(this.multipleSelection).then((response) => {
            this.$message({
              type: "success",
              message: `${response.message}`,
            });
            this.list(this.currentPage);
            this.getTotal();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    deleteHandler(data) {
      this.$confirm(
        "此操作将永久删除该套试卷及相关考试记录，是否继续？",
        "提示",
        { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" }
      )
        .then(() => {
          zhiZhaoApi.delete(data.id).then((response) => {
            this.$message({
              type: "success",
              message: `${response.message}`,
            });
            this.list(1);
            this.getTotal();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    detail(data) {
      this.$router.push({
        path: `/testResult/index`,
        query: { title: data.title },
      });
    },
    handleCurrentChange(currentPage) {
      this.list(currentPage);
    },
    submit: async function () {
      this.list(this.currentPage);
    },
    list(currentPage) {
      zhiZhaoApi
        .getResultList(
          this.form.title,
          this.form.time,
          currentPage,
          this.pageSize
        )
        .then((res) => {
          this.tableData = res.data;
        });
    },
    getTotal() {
      zhiZhaoApi.getResultTotal(this.form.title, this.form.time).then((res) => {
        this.total = res.data;
      });
    },
    reset: async function () {
      this.form = { number: "", time: "" };
    },
    getSubjects: async function () {
      const res = await subjectApi.getAll();
      this.subjects = res.data;
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.list(1);
    this.getTotal();
    this.getSubjects();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
